// pages/skip/skip.js
//获取应用实例
const app = getApp();
const utils = require('../../utils/util.js');
const post = utils.post;
const sdk = require('../../utils/sdk.js')
const getCurrentPageUrlWithArgs = utils.getCurrentPageUrlWithArgs;

Page({
    data: {
        scene: '',
        appid: '',
        path: '',
        uid: '',
        weappid: '',
        picurl: '',
        get_user_info: 0,
        play_time_start: 0,
        play_time_end: 0,
        play_time: 0,
        pls: '',
        flag: 'none',
        name: 'APP',
        jump_time_start: 0,
        jump_time_end: 0,
        jump_play_time: 0
    },
    onLoad: function(options) {
        let that = this;
        if (options.scene) {
            this.data.scene = options.scene;
            let _scene = decodeURIComponent(this.data.scene).split(':');
            this.data.uid = _scene[0];
            this.data.weappid = _scene[1];
            wx.setStorageSync('weapp_uid', this.data.uid);
            wx.removeStorageSync('pls_' + this.data.uid + '_' + this.data.weappid);
            if (_scene.length >= 3) {
                //console.log(_scene);
                let _pls = _scene[2];
                if (_pls) {
                    this.data.pls = _pls;
                    wx.setStorageSync('pls_' + this.data.uid + '_' + this.data.weappid, this.data.pls);
                    this.setData({
                        flag: 'flex',
                        name: '公众号'
                    });
                }
            }
        } else {
            if (options.uid && options.weappid) {
                this.data.uid = options.uid;
                this.data.weappid = options.weappid;
                wx.setStorageSync('weapp_uid', this.data.uid);
            }
            wx.removeStorageSync('pls_' + this.data.uid + '_' + this.data.weappid);
            if (options.pls) {
                this.data.pls = options.pls;
                wx.setStorageSync('pls_' + this.data.uid + '_' + this.data.weappid, this.data.pls);
                this.setData({
                    flag: 'flex',
                    name: 'APP'
                });
                if (options.from && 'jlist' == options.from) {
                    this.setData({
                        flag: 'flex',
                        name: ''
                    });
                }
            }
        }

        this.fetchData();
    },

    launchAppError: function(e) {
        wx.showToast({
            title: e.detail.errMsg,
            icon: 'none',
        });
    },

    fetchData() {
        let that = this;
        if (that.data.uid && that.data.weappid) {
            let uid = that.data.uid;
            let weappid = that.data.weappid;
            let p = {
                m: 'weapp_info',
                uid: uid,
                weappid: weappid
            };
            post(p).then(res => {
                // console.log(res);
                if (res.r == 0) {
                    //if (res.result.get_user_info == 1) {
                    that.handleGetUserInfo();
                    //}

                    var _path = res.result.page;
                    if (_path.indexOf('?') != -1) { // 包含问号
                        _path += '&uid=' + that.data.uid + '&weappid=' + that.data.weappid;
                    } else { // 不包含问号
                        _path += '?uid=' + that.data.uid + '&weappid=' + that.data.weappid;
                    }

                    //console.log(that.data);

                    that.setData({
                        appid: res.result.appid,
                        path: _path,
                        picurl: res.result.img_bg,
                        get_user_info: res.result.get_user_info
                    });
                    // wx.navigateToMiniProgram({
                    //     appId: res.result.appid,
                    //     path: _path,
                    //     success() {
                    //         that.handleLeave();
                    //     },
                    //     fail() {
                    //         console.log('failed')
                    //     }
                    // })
                }
            });
        }
    },
    handleGetUserInfo() {
        let that = this;

        // 2.获取用户信息
        wx.login({
            success(res) {
                var code = res.code;
                wx.getUserInfo({
                    success(res2) {
                        var encryptedData = res2.encryptedData;
                        var iv = res2.iv;
                        var p = {
                            m: 'jump_get_userinfo',
                            code: code,
                            encryptedData: encryptedData,
                            iv: iv,
                            uid: that.data.uid,
                            weappid: that.data.weappid
                        };
                        post(p).then(res3 => {
                            if (0 == res3.r) {
                                //console.log(res3);
                                var aid = res3.aid;
                                var _path = that.data.path;
                                if (_path.indexOf('?') != -1) { // 包含问号
                                    _path += '&aid=' + aid;
                                } else { // 不包含问号
                                    _path += '?aid=' + aid;
                                }
                                that.setData({
                                    path: _path,
                                });

                                var userinfo = res3.userinfo;
                                var weapp_openid = userinfo.openId;
                                wx.setStorageSync('weapp_openid', weapp_openid); // 桔子派的openId

                                wx.setStorageSync('_userinfo', res3.userinfo);
                                wx.setStorageSync('device_info', wx.getSystemInfoSync());
                            }
                        })
                    }
                })
            }
        })
    },
    handleLeave(e) {
        let that = this;
        let timestamp = parseInt(new Date().getTime() / 1000);
        let content = {
            x: e.detail.x ? e.detail.x : 0,
            y: e.detail.y ? e.detail.y : 0,
            longitude: app.globalData.longitude ? app.globalData.longitude : 0,
            latitude: app.globalData.latitude ? app.globalData.latitude : 0,
            userinfo: wx.getStorageSync('_userinfo'),
            device_info: wx.getStorageSync('device_info')
        };
        content = JSON.stringify(content);
        let p = {};
        if (that.data.get_user_info == 0) {
            p = {
                m: 'invoke',
                type: 'jump',
                content: content,
                uid: that.data.uid,
                weappid: that.data.weappid
            };
        } else if (that.data.get_user_info == 1) {
            p = {
                m: 'invoke',
                type: 'jump',
                content: content,
                uid: that.data.uid,
                weappid: that.data.weappid
            };
        }

        if (that.data.pls) { // 自己试玩
            that.data.play_time_start = parseInt(new Date().getTime() / 1000);
            wx.setStorageSync('play_time_start_' + that.data.uid + '_' + that.data.weappid, that.data.play_time_start);

            // 发送一个去试玩的事件
            let content = {
                x: e.detail.x ? e.detail.x : 0,
                y: e.detail.y ? e.detail.y : 0,
                longitude: app.globalData.longitude ? app.globalData.longitude : 0,
                latitude: app.globalData.latitude ? app.globalData.latitude : 0,
                userinfo: wx.getStorageSync('_userinfo'),
                device_info: wx.getStorageSync('device_info'),
                pls: that.data.pls,
            };

            content = JSON.stringify(content);

            let p = {
                m: 'invoke',
                type: 'go_play',
                content: content,
                uid: that.data.uid,
                weappid: that.data.weappid
            };

            post(p).then(res => {
                //console.log(res);
                if (res.r == 0) {}
            })
        } else {
            that.data.jump_time_start = parseInt(new Date().getTime() / 1000);
            wx.setStorageSync('jump_time_start_' + that.data.uid + '_' + that.data.weappid, that.data.jump_time_start);

            //if (that.data.appid != wx.getStorageSync('appid_' + that.data.appid)) {
            post(p).then(res => {
                    //console.log(res);
                    if (res.r == 0) {
                        wx.setStorageSync('appid_' + that.data.appid, that.data.appid)
                    }
                })
                //}
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        this.data.play_time_start = 0;
        this.data.play_time_end = 0;
        this.play_time = 0;

        this.data.jump_time_start = 0;
        this.data.jump_time_end = 0;

        wx.getStorageInfo({
            success: function(res) {
                //console.log(res.keys)
                for (var i = 0; i < res.keys.length; i++) {
                    var key = res.keys[i];
                    //console.log(key);
                    if (0 == key.indexOf('play_time_start_')) {
                        wx.removeStorageSync(key);
                    } else if (0 == key.indexOf('play_time_end_')) {
                        wx.removeStorageSync(key);
                    } else if (0 == key.indexOf('jump_time_start_')) {
                        wx.removeStorageSync(key);
                    } else if (0 == key.indexOf('jump_time_end_')) {
                        wx.removeStorageSync(key);
                    }
                }
            }
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this;
        if (that.data.uid && that.data.weappid) {
            let pls = wx.getStorageSync('pls_' + that.data.uid + '_' + that.data.weappid);
            if (pls) { // 自己试玩
                that.data.pls = pls;
                let play_time_start = wx.getStorageSync('play_time_start_' + that.data.uid + '_' + that.data.weappid);
                if (play_time_start && play_time_start > 0) {
                    that.data.play_time_start = play_time_start;

                    that.data.play_time_end = parseInt(new Date().getTime() / 1000);
                    wx.setStorageSync('play_time_end_' + that.data.uid + '_' + that.data.weappid, that.data.play_time_end);
                    let play_time = that.data.play_time_end - that.data.play_time_start;
                    that.setData({
                        play_time: play_time
                    });

                    let content = {
                        userinfo: wx.getStorageSync('_userinfo'),
                        device_info: wx.getStorageSync('device_info'),
                        pls: that.data.pls,
                        play_time: that.data.play_time
                    };

                    content = JSON.stringify(content);

                    let p = {
                        m: 'invoke',
                        type: 'play',
                        content: content,
                        uid: that.data.uid,
                        weappid: that.data.weappid
                    };

                    post(p).then(res => {
                        //console.log(res);

                        //wx.removeStorageSync('pls_' + that.data.uid + '_' + that.data.weappid);
                        wx.removeStorageSync('play_time_start_' + that.data.uid + '_' + that.data.weappid);
                        wx.removeStorageSync('play_time_end_' + that.data.uid + '_' + that.data.weappid);

                        if (play_time < 30) {
                            wx.showModal({
                                content: '需要试玩30秒以上才可赚钱!',
                                showCancel: false
                            });
                        } else {
                            wx.showModal({
                                content: '试玩结束，请返回' + that.data.name + '试玩其它小程序!',
                                showCancel: false
                            });
                        }
                    })
                }
            } else {
                let jump_time_start = wx.getStorageSync('jump_time_start_' + that.data.uid + '_' + that.data.weappid);
                if (jump_time_start && jump_time_start > 0) {
                    that.data.jump_time_start = jump_time_start;

                    that.data.jump_time_end = parseInt(new Date().getTime() / 1000);
                    wx.setStorageSync('jump_time_end_' + that.data.uid + '_' + that.data.weappid, that.data.jump_time_end);
                    let jump_play_time = that.data.jump_time_end - that.data.jump_time_start;
                    that.setData({
                        jump_play_time: jump_play_time
                    });

                    let content = {
                        userinfo: wx.getStorageSync('_userinfo'),
                        device_info: wx.getStorageSync('device_info')
                    };

                    content = JSON.stringify(content);

                    let p = {
                        m: 'invoke',
                        type: 'jump_back', // 分享玩（游客玩）返回
                        content: content,
                        uid: that.data.uid,
                        weappid: that.data.weappid
                    };

                    post(p).then(res => {
                        wx.removeStorageSync('jump_time_start_' + that.data.uid + '_' + that.data.weappid);
                        wx.removeStorageSync('jump_time_end_' + that.data.uid + '_' + that.data.weappid);

                        if (jump_play_time < 30) {
                          
                        } else {
                          wx.navigateBack({
                            delta: 1
                          });
                        }
                    });
                }
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {},
    errorGg: function(e) {
        // console.log(e.detail.errCode);
        // console.log(e.detail.errMsg);
        let that = this;
        if (that.data.uid && that.data.weappid) {
            let content = {
                errCode: e.detail.errCode,
                errMsg: e.detail.errMsg,
                userinfo: wx.getStorageSync('_userinfo'),
                device_info: wx.getStorageSync('device_info')
            };

            content = JSON.stringify(content);
            let p = {
                m: 'invoke',
                type: 'ad_err',
                content: content,
                uid: that.data.uid,
                weappid: that.data.weappid
            };
            post(p).then(res => {
                // console.log(res)
            })
        }
    },
    submitFormId(e) {
        // console.log(e);
        let formId = e.detail.formId;
        let button = e.detail.target.dataset.name;
        let page = getCurrentPageUrlWithArgs();
        let that = this;
        let p = {
            m: 'colform',
            uid: that.data.uid,
            openid: wx.getStorageSync('weapp_openid'),
            formId: formId
        };
        if (page && page.length > 0) {
            p.page = page;
        }
        if (button && button.length > 0) {
            p.button = button;
        }
        //console.log(p)
        post(p).then(res => {})
    }
})